#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#include "sqlite3.h"

//创建或打开数据库、建表
int database_init(sqlite3 **db)
{
	int		rv = -1;
	char		*sql;
	char		*zErrMsg = 0;

	//打开数据库
	rv = sqlite3_open("temperature.db", db);
	if(rv < 0)
	{
		printf("Open database failure: %s\n", strerror(errno));
		return -1;
	}

	//建表
	sql = "CREATE TABLE IF NOT EXISTS TEMPER(     "	\
	"ID INTEGER   PRIMARY KEY	AUTOINCREMENT,"	\
	"SN 	      CHAR(10) 		NOT NULL,"	\
	"DATATIME     CHAR(50)		NOT NULL,"	\
	"TEMPERATURE  CHAR(10)  	NOT NULL);"	;

	rv = sqlite3_exec(*db, sql, 0, 0, &zErrMsg);
	if(rv != SQLITE_OK)
	{
		printf("SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
		return -2;
	}
	else
	{
		printf("Create database and table OK!\n");
	}

	return 0;

}

int save_data_to_database(sqlite3 *db, char *buf)
{
	int		rv = -1;
	char		p[128];
	char		*ID, *datatime, *temp;
	char		*zErrMsg = 0;

	ID = strtok(buf, "/");
	datatime = strtok(NULL, "/");
	temp = strtok(NULL, "/");

	//插入数据
	snprintf(p, 128, "INSERT INTO TEMPER VALUES(NULL, '%s', '%s', '%s');", ID, datatime, temp);

	rv = sqlite3_exec(db, p, 0, 0, &zErrMsg);
	if(rv != SQLITE_OK)
	{
		printf("SQL error: %s\n", zErrMsg);
		return -3;
	}
	else
	{
		printf("Insert data to database OK!\n");
	}

	return 0;
}


